﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Data;
using System.Web;
using System.Globalization;

namespace yncTech.Common
{
    public static class WebHelperEx
    {
        /// <summary>
        /// 对Repeater数据绑定进行扩展当字符串长度大于指定值返回 Xxxxxx...
        /// </summary>
        /// <param name="str"></param>
        /// <param name="maxLength"></param>
        /// <returns></returns>
        public static string ShowMaxStringEx(this Object str, int maxLength)
        {
            if (str == null)
            {
                return "";
            }
            if (str.ToString().Length > maxLength)
            {
                return str.ToString().Substring(0, maxLength) + "...";
            }
            return str.ToString();
        }

        /// <summary>
        /// 对Repeater数据绑定进行扩展格式化日期格式
        /// </summary>
        /// <param name="date"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public static string FormatDate(this Object date, string format)
        {
            var newDate = date as DateTime?;
            if (newDate.HasValue)
            {
                return newDate.Value.ToString(format);
            }
            return "";
        }

        /// <summary>
        /// 将String转换为日期
        /// </summary>
        /// <param name="dateStr"></param>
        /// <returns></returns>
        public static DateTime ToDate(this string dateStr)
        {
            return ToDate(dateStr, "yyyy-MM-dd");
        }

        /// <summary>
        /// 将String转换为日期
        /// </summary>
        /// <param name="dateStr"></param>
        /// <returns></returns>
        public static DateTime ToDate(this string dateStr, string datePattern)
        {
            DateTimeFormatInfo format = new DateTimeFormatInfo();
            format.ShortDatePattern = datePattern;
            return DateTime.Parse(dateStr, format);
        }
    }
    public class WebHelper
    {
        public static void ReLogin(string url)
        {
            string script = @"<script language='JavaScript'>window.top.location.href='{0}';</script>";

            HttpContext.Current.Response.Write(string.Format(script, url));
        }

        public static void GotoParent()
        {
            HttpContext.Current.Response.Redirect(HttpContext.Current.Request.ServerVariables["HTTP_REFERER"]);
        }

        public static void GotoParent(string message)
        {
            string script = "<script language='JavaScript'>alert('{0}');window.location.href='{1}';</script>";


            HttpContext.Current.Response.Write(string.Format(script, message.Replace("'","\\'"), HttpContext.Current.Request.ServerVariables["HTTP_REFERER"]));
        }

        public static void CloseDialog()
        {
            CloseDialog(false);
        }


        /// <summary>
        /// 关闭打开的了窗口
        /// </summary>
        /// <param name="isRefresh">是否需要刷新首页</param>
        public static void CloseDialog(bool isRefresh, Dictionary<string, string> param)
        {
            string urlParam = "null";
            if (param != null && param.Keys.Count > 0)
            {
                urlParam = "";
                foreach (var key in param.Keys)
                {
                    urlParam += key + "=" + param[key] + "&";
                }
            }

            string script = @"<script language='JavaScript'>window.top.CloseDialog({0},'{1}');</script>";

            HttpContext.Current.Response.Write(string.Format(script, isRefresh ? "true" : "false", urlParam.TrimEnd('&')));
        }

        /// <summary>
        /// 关闭打开的了窗口
        /// </summary>
        /// <param name="isRefresh">是否需要刷新首页</param>
        public static void CloseDialog(bool isRefresh)
        {
            string script = @"<script language='JavaScript'>window.top.CloseDialog({0});</script>";

            HttpContext.Current.Response.Write(string.Format(script, isRefresh ? "true" : "false"));
        }

        public static void RefreshOpener()
        {
            string script = @"<script language='JavaScript'>window.top.Refresh();</script>";

            HttpContext.Current.Response.Write(script);
        }

        public static void ShowMessageBox(Page page, string message)
        {
            string script = @"<script language='JavaScript'>alert('{0}');</script>";
            page.ClientScript.RegisterStartupScript(page.GetType(), "showMessageBox", string.Format(script, message));
        }

        public static string GetDate(object date)
        {
            return GetDate(date, "yyyy-MM-dd");
        }

        public static string GetDate(object date, string format)
        {
            DateTime? dateTime = (DateTime?)date;
            if (dateTime.HasValue)
            {
                return dateTime.Value.ToString(format);
            }

            return "date error";

        }

        public static string GetDate(DateTime date, string format)
        {
            return date.ToString(format);
        }

        public static string GetLink(string text,string cssClass,bool showText, string type, string url, object obj, int width, int height, params string[] args)
        {
            string script = "<a title='"+text+"' class=\""+cssClass+"\" href=\"" + "javascript:OpenWindow('";
            script += string.Format(text + "','{0}','", type);
            if (url.IndexOf("?") > 0)
            {
                url += "&type=" + type;
            }
            else
            {
                url += "?type=" + type;
            }
            if (obj != null)
            {
                bool flag = obj.GetType().Equals(typeof(DataRowView));
                object[] pars = new object[args.Length];
                if (flag)
                {
                    DataRowView dv = obj as DataRowView;
                    for (int i = 0; i < args.Length; i++)
                    {
                        url += "&" + args[i] + "={" + i + "}";
                        pars[i] = dv[args[i].ToString()];
                    }
                }
                else
                {
                    for (int i = 0; i < args.Length; i++)
                    {
                        url += "&" + args[i] + "={" + i + "}";
                        pars[i] = Reflector.GetPropertyValue(obj, args[i].ToString());
                    }
                }
                script += string.Format(url, pars);
            }
            else
            {
                script += url;
            }

            if (showText)
            {
                script += "'," + width + "," + height + ")\">" + text + "</a>";
            }
            else
            {
                script += "'," + width + "," + height + ")\"></a>";
            }
            return script;
        }

        public static string GetLink(string text, string type, string url, object obj, int width, int height, params string[] args)
        {
            return GetLink(text, "style4",true,type, url, obj, width, height, args);
        }
        public static string GetConfirmLink(string text,  string type, string url, object obj, string message, params string[] args)
        {
            return GetConfirmLink(text, "style4",true, type, url, obj, message, args);
        }
        public static string GetConfirmLink(string text,string cssClass,bool showText, string type, string url, object obj, string message, params string[] args)
        {
            string script = string.Format("<a title='"+text+"' class='" + cssClass + "' onclick=\"javascript:return confirm('{0}?');\" href=\"", message);
            if (obj != null)
            {
                bool flag = obj.GetType().Equals(typeof(DataRowView));

                object[] pars = new object[args.Length];


                if (url.IndexOf("?") > 0)
                {
                    url += "&type=" + type;
                }
                else
                {
                    url += "?type=" + type;
                }
                if (flag)
                {
                    DataRowView dv = obj as DataRowView;
                    for (int i = 0; i < args.Length; i++)
                    {
                        url += "&" + args[i] + "={" + i + "}";
                        pars[i] = dv[args[i].ToString()];
                    }
                }
                else
                {
                    for (int i = 0; i < args.Length; i++)
                    {
                        url += "&" + args[i] + "={" + i + "}";
                        pars[i] = Reflector.GetPropertyValue(obj, args[i].ToString());
                    }
                }

                script += string.Format(url, pars);
            }
            else
            {
                script += url;
            }

            if (showText)
            {
                script += string.Format("\">{0}</a>", text);
            }
            else
            {

                script += "\"></a>";
            }

            return script;
        }

        public static string GetNewTabLink(string text, string type, string url, object obj, params string[] args)
        {
            string script = "<a class=\"style4\" title='"+text+"' href=\"" + "javascript:OpenNewTab('";
            script += text + "','";
            if (url.IndexOf("?") > 0)
            {
                url += "&type=" + type;
            }
            else
            {
                url += "?type=" + type;
            }
            if (obj != null)
            {
                bool flag = obj.GetType().Equals(typeof(DataRowView));
                object[] pars = new object[args.Length];
                if (flag)
                {
                    DataRowView dv = obj as DataRowView;
                    for (int i = 0; i < args.Length; i++)
                    {
                        url += "&" + args[i] + "={" + i + "}";
                        pars[i] = dv[args[i].ToString()];
                    }
                }
                else
                {
                    for (int i = 0; i < args.Length; i++)
                    {
                        url += "&" + args[i] + "={" + i + "}";
                        pars[i] = Reflector.GetPropertyValue(obj, args[i].ToString());
                    }
                }
                script += string.Format(url, pars);
            }
            else
            {
                script += url;
            }

            script += "')\">" + "<span>" + text + "</span>" + "</a>";
            return script;
        }


        #region GetCookie

        public static string GetCookie(string cookieName)
        {
            HttpCookie httpCookie = HttpContext.Current.Request.Cookies[cookieName];
            if (httpCookie != null)
            {
                return httpCookie.Value;
            }
            else
            {
                return null;
            }
        }

        #endregion

        #region RemoveCookie

        public static void RemoveCookie(string cookieName)
        {
            HttpContext.Current.Response.Cookies.Remove(cookieName);
            HttpContext.Current.Request.Cookies.Remove(cookieName);
        }

        #endregion

        public static string RootUrl()
        {
            return HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority;
        }

        #region SetCookie

        public static void SetCookie(string cookieName, string value)
        {
            SetCookie(cookieName, value, DateTime.Now.AddDays(30));
        }



        public static void SetCookie(string cookieName, string value, DateTime expires)
        {
            RemoveCookie(cookieName);
            HttpCookie httpCookie = new HttpCookie(cookieName, value);
            httpCookie.Expires = expires;
            HttpContext.Current.Response.Cookies.Add(httpCookie);
        }

        #endregion

        #region GetBytes
        /// <summary>
        /// Convert byte[] to string
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string GetString(byte[] data)
        {
            string result = "";
            if (data != null)
            {
                result = Encoding.Default.GetString(data);
            }
            return result;
        }
        #endregion

        #region GetBytes
        /// <summary>
        /// Convert string to bytes
        /// </summary>
        /// <param name="str">string</param>
        /// <returns></returns>
        public static byte[] GetBytes(string str)
        {
            return Encoding.Default.GetBytes(str);
        }
        #endregion

        public static DateTime ConvertToDate(string date)
        {
            return DateTime.Parse(date);
        }

        /// <summary>
        /// Get the formated date string
        /// </summary>
        /// <param name="date"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public static string FormatDate(object date, string format)
        {
            var newDate = date as DateTime?;
            if (newDate.HasValue)
            {
                return newDate.Value.ToString(format);
            }
            return date.ToString();
        }


        public static string ShowMaxString(object str, int maxLength)
        {
            if (str == null)
            {
                return "";
            }
            if (str.ToString().Length > maxLength)
            {
                return str.ToString().Substring(0, maxLength) + "...";
            }
            return str.ToString();

        }

        /// <summary>
        /// 检查Datatable是否有数据
        /// </summary>
        /// <param name="table"></param>
        /// <returns></returns>
        public static bool CheckIsNotEmpty(DataTable table)
        {
            if (table != null && table.Rows.Count > 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 检查Dataset中是否有数据
        /// </summary>
        /// <param name="ods"></param>
        /// <param name="tableIndex"></param>
        /// <returns></returns>
        public static bool CheckIsNotEmpty(DataSet ods, int tableIndex = 0)
        {
            if (ods != null && ods.Tables.Count > 0 && ods.Tables[tableIndex].Rows.Count > 0)
            {
                return true;
            }
            return false;
        }

        //public static string ToJSON<T>(T obj)
        //{
        //    string json = JsonConvert.SerializeObject(obj);
        //    return json;
        //}





    }
}
